import 'package:backdrop/backdrop.dart';
import 'package:flutter/material.dart';
import 'package:flutter_2b_client/components/FormItem.dart';
import 'package:flutter_2b_client/model/IntIdAndName.dart';
import 'package:flutter_2b_client/utils/Page.dart';
import 'package:flutter_2b_client/utils/PagingUtils.dart';
import 'package:flutter_hooks/flutter_hooks.dart';
import 'package:go_router/go_router.dart';

import '../apis/MarketGoodsApi.dart';
import '../components/CheckboxWrap.dart';
import '../components/FilterBackLayerLayout.dart';
import '../components/GoodsListItem.dart';
import '../components/PageableQueryFrontLayer.dart';

class MarketGoodsPage extends HookWidget {
  final int marketId;
  final String marketName;

  const MarketGoodsPage({
    Key? key,
    required this.marketId,
    required this.marketName,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    var pagingController =
        usePagingController<Pageable, QueryMarketGoodsResponse>(
            firstPageKey: Pageable());
    var totalElementsState = useState(0);
    var goodsFilterDataState = useState(const QueryMarketGoodsRequest());
    usePagingControllerListener(
        pagingController,
        (pageable) => marketGoodsApi
                .queryMarketGoods(
                    marketId, goodsFilterDataState.value, pageable)
                .then((value) {
              totalElementsState.value = value.totalElements;
              return value;
            }),
        null,
        [
          goodsFilterDataState.value,
        ]);

    var textEditingController = useTextEditingController();

    return BackdropScaffold(
      backLayerBackgroundColor: Theme.of(context).colorScheme.primaryContainer,
      appBar: AppBar(
        title: Text("$marketName商品"),
        backgroundColor: Theme.of(context).colorScheme.primaryContainer,
        actions: [
          BackdropToggleButton(
            icon: AnimatedIcons.close_menu,
            color: goodsFilterDataState.value.hasAnyFilter
                ? Theme.of(context).colorScheme.tertiary
                : Theme.of(context).colorScheme.onPrimaryContainer,
          ),
          IconButton(
            onPressed: () async {
              var barcode = await context.push("/scanBarcode") as String?;
              if (barcode != null) {
                textEditingController.text = barcode;
                goodsFilterDataState.value =
                    goodsFilterDataState.value.copyWith(nameOrBarcode: barcode);
              }
            },
            icon: const Icon(Icons.document_scanner_rounded),
          ),
        ],
      ),
      backLayer: MarketGoodsFilterBackLayer(
        marketId: marketId,
        nameOrBarcodeTextEditingController: textEditingController,
        onConfirm: (QueryMarketGoodsRequest data) {
          goodsFilterDataState.value = data;
        },
      ),
      frontLayer: PageableQueryFrontLayer(
        total: totalElementsState.value,
        pagingController: pagingController,
        itemBuilder:
            (BuildContext context, QueryMarketGoodsResponse item, int index) {
          return ListTile(
            title: Text(item.name),
            dense: true,
            subtitle: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(item.barcode),
                DefaultTextStyle(
                  style: DefaultTextStyle.of(context).style.copyWith(
                      color: Theme.of(context).colorScheme.inverseSurface),
                  child: Row(
                    children: [
                      FixedWidthKeyPair("数量", item.amountInMarket.toString()),
                      FixedWidthKeyPair("库存", item.amount.toString()),
                      FixedWidthKeyPair("零售价", item.price.toString()),
                    ],
                  ),
                ),
              ],
            ),
          );
        },
        resource: "商品",
      ),
    );
  }
}

class MarketGoodsFilterBackLayer extends HookWidget {
  final int marketId;
  final void Function(QueryMarketGoodsRequest data) onConfirm;
  final TextEditingController nameOrBarcodeTextEditingController;

  const MarketGoodsFilterBackLayer(
      {Key? key,
      required this.marketId,
      required this.onConfirm,
      required this.nameOrBarcodeTextEditingController})
      : super(key: key);

  @override
  Widget build(BuildContext context) {
    var textState = useState("");

    var brandsState = useState<List<IntIdAndName>>([]);
    useEffect(() {
      marketGoodsApi
          .getAllGoodsBrands(marketId)
          .then((value) => brandsState.value = value);
      return null;
    }, []);
    final selectedBrandIdsState = useState<List<int>>([]);

    var categoriesState = useState<List<IntIdAndName>>([]);
    useEffect(() {
      marketGoodsApi
          .getAllGoodsCategories(marketId)
          .then((value) => categoriesState.value = value);
      return null;
    }, []);
    final selectedCategoryIdsState = useState<List<int>>([]);

    var factoriesState = useState<List<IntIdAndName>>([]);
    useEffect(() {
      marketGoodsApi
          .getAllGoodsFactories(marketId)
          .then((value) => factoriesState.value = value);
      return null;
    }, []);
    final selectedFactoryIdsState = useState<List<int>>([]);

    final onlyNewState = useState(false);
    return FilterBackLayerLayout(
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          FormItem(
            label: "条码和名称",
            child: Padding(
              padding: const EdgeInsets.only(top: 8.0),
              child: TextField(
                controller: nameOrBarcodeTextEditingController,
                onChanged: (value) => textState.value = value,
                decoration: const InputDecoration(
                    border: OutlineInputBorder(gapPadding: 0),
                    isDense: true,
                    contentPadding:
                        EdgeInsets.symmetric(horizontal: 8, vertical: 6)),
              ),
            ),
          ),
          if (brandsState.value.isNotEmpty)
            FormItem(
              label: "品牌",
              child: CheckboxWrap(
                elements: brandsState.value,
                getKey: (IntIdAndName e) {
                  return e.id;
                },
                getLabel: (IntIdAndName e) {
                  return e.name;
                },
                selectedKeys: selectedBrandIdsState.value,
                onChange: (keys) => selectedBrandIdsState.value = keys,
              ),
            ),
          if (categoriesState.value.isNotEmpty)
            FormItem(
              label: "分类",
              child: CheckboxWrap(
                elements: categoriesState.value,
                getKey: (IntIdAndName e) {
                  return e.id;
                },
                getLabel: (IntIdAndName e) {
                  return e.name;
                },
                selectedKeys: selectedCategoryIdsState.value,
                onChange: (keys) => selectedCategoryIdsState.value = keys,
              ),
            ),
          if (factoriesState.value.isNotEmpty)
            FormItem(
              label: "厂商",
              child: CheckboxWrap(
                elements: factoriesState.value,
                getKey: (IntIdAndName e) {
                  return e.id;
                },
                getLabel: (IntIdAndName e) {
                  return e.name;
                },
                selectedKeys: selectedFactoryIdsState.value,
                onChange: (keys) => selectedFactoryIdsState.value = keys,
              ),
            ),
        ],
      ),
      onConfirm: () {
        onConfirm(QueryMarketGoodsRequest(
          brandIds: selectedBrandIdsState.value,
          categoryIds: selectedCategoryIdsState.value,
          nameOrBarcode: textState.value.isEmpty ? null : textState.value,
          factoryIds: selectedFactoryIdsState.value,
        ));
        Backdrop.of(context).concealBackLayer();
      },
      onClear: () {
        selectedCategoryIdsState.value = [];
        selectedBrandIdsState.value = [];
        textState.value = "";
      },
    );
  }
}
